package com.funcourse.demo.business;

import com.funcourse.demo.model.repo.room.RoomNumberRepo;
import com.funcourse.demo.model.room.RoomNumber;
import com.funcourse.demo.util.RandomString;

import java.util.List;
import java.util.Random;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
@Slf4j
public class RoomNumberAllocator {

  @Autowired
  RoomNumberRepo roomNumberRepo;

  public String allocateNumberForRoom(String roomId){
    RandomString randomString = new RandomString(6,new Random(),RandomString.digits);
    String roomNumber = randomString.nextString();
    List<RoomNumber> byRoomNo = roomNumberRepo.findByRoomNo(roomNumber);
    int retryTimes = 0;
    while (!CollectionUtils.isEmpty(byRoomNo)){
      roomNumber = randomString.nextString();
      byRoomNo = roomNumberRepo.findByRoomNo(roomNumber);
      retryTimes ++;
      if(retryTimes>15){
        log.error("RoomNumberAllocator WARNING TOO MANY ROOMS ARE RUNNING!!!!");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          log.error("waiting other room closed interupteed");
        }
      }
    }
    return roomNumber;
  }

}
